package com.ruoyi.parkingcar.controller;
import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.ruoyi.parkingcar.domain.ParkOrder;
import com.ruoyi.parkingcar.service.IParkOrderService;
import com.ruoyi.parkingcar.util.AliPayConfig;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cuncun
 * @create 2025-01-14 下午10:56
 */
@RestController
@RequestMapping("/alipay") //通过这个接口来支付宝给我们返回数据
public class AliPayController {

    //支付宝沙箱网关地址
    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    //签名方式
    private static final String SIGN_TYPE ="RSA2";

    @Resource
    private AliPayConfig aliPayConfig;//支付宝的配置信息

    @Resource
    private IParkOrderService parkOrderService;

    @GetMapping("/pay")  //alipay/pay?orderNo=xxx 前端点击支付调用该接口
    //根据orderNo查询订单信息，这里orderNo要唯一的
    public void pay(String orderNo,HttpServletResponse httpResponse) throws Exception {
        ParkOrder parkOrder = new ParkOrder();
        parkOrder.setOrderNo(orderNo);
        //查询订单信息
        List<ParkOrder> orders = parkOrderService.selects(parkOrder);
        System.out.println("订单信息: " + orders);//在这里打印看看有没有查到对应的订单信息，因为如果没有拿到订单金额，就会失败
        //没有用户订单信息就结束方法
        if (orders == null) {
            return ;
        }
        //1.创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        //2.创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 发送请求的 Request类
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());//这是设置支付宝支付请求的通知回调地址 就要当你支付成功，会调用该方法
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", orders.get(0).getOrderNo()); // 我们自己生成的订单编号
        bizContent.set("total_amount", orders.get(0).getCost());// 订单的总金额
        bizContent.set("subject", "完成支付");// 支付的名称
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY"); // 固定配置
        request.setBizContent(bizContent.toString());
        request.setReturnUrl("http://localhost:8000/#/Order");//支付完成后自动跳转到本地页面的路径 *这个写自己的路径
        //执行请求，拿到响应的结果，返回给浏览器 支付宝官方页面
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        // 将表单内容设置为响应内容
        httpResponse.setContentType("text/html;charset=" + CHARSET);  // 设置字符编码为UTF-8
        httpResponse.getWriter().write(form);  // 将支付宝表单内容直接写入到响应
        httpResponse.getWriter().flush();  // 刷新输出流，确保表单数据输出
        httpResponse.getWriter().close();  // 关闭输出流


    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        System.out.println("e++++++++++++++++++++++++++++++++++++++++++++");
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));

            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content,sign,aliPayConfig.getAlipayPublicKey(),"UTF-8");
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                String tradeNo = params.get("out_trade_no");//订单编号
                String gmtPayment = params.get("gmt_payment");//支付时间
                String alipayTradeNo = params.get("trade_no");//支付宝交易编号

                //这个方法修改的就这只有这里  修改自己表里的信息，我这就把状态改为已支付，然后拿到支付宝传过来的编号，和支付时间
                // 更新订单为已支付，设a置支付信息
                ParkOrder parkOrder = new ParkOrder();
                parkOrder.setOrderNo(tradeNo);
                List<ParkOrder> orders = parkOrderService.selects(parkOrder);
                //修改用户订单信息

                orders.get(0).setOrderStatus(0);
                orders.get(0).setPayTime(gmtPayment);
//                order.setCheckoutTime(params.get("gmt_payment"));
                System.out.println(orders.get(0)+"===============================================");
                parkOrderService.updateOrder(orders.get(0));//更新数据库
            }
        }
        return "success";
    }

}

